﻿using CefSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Ledict.ConditionExtract.Config.Controls
{
    public partial class webBrowerUser : UserControl
    {
        /// <summary>
        ///保存成功事件
        /// </summary>
        public event EventHandler<string> SaveSuccess;
        RegexJsDialogHandler regexJsDialogHandler = new RegexJsDialogHandler();
        public webBrowerUser()
        {
            InitializeComponent();
            regexJsDialogHandler.MessageAlert += RegexJsDialogHandler_SaveSuccess;
            browserRegex.JsDialogHandler = regexJsDialogHandler;
        }

        private void RegexJsDialogHandler_SaveSuccess(object sender, string e)
        {
            if (e.Contains("成功"))
            {
                if (e.Contains("-"))
                {
                    var code = e.Split('-')[1];                    
                    SaveSuccess?.Invoke(this,code);
                }
            }
        }
        /// <summary>
        /// 加载地址
        /// </summary>
        /// <param name="url">URL地址</param>
        public virtual void LoadUrl(string url)
        {
            try
            {
                browserRegex.Load(url);
            }
            catch (Exception ex)
            {
                MessageBox.Show("绑定地址出错:" + ex.Message);
            }
        }
    }

    public class RegexJsDialogHandler : IJsDialogHandler
    {
        /// <summary>
        ///保存成功事件
        /// </summary>
        public event EventHandler<string> MessageAlert;
        public bool OnBeforeUnloadDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, string messageText, bool isReload, IJsDialogCallback callback)
        {
            return true;
        }

        public void OnDialogClosed(IWebBrowser chromiumWebBrowser, IBrowser browser)
        {

        }

        public bool OnJSDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage)
        {
            MessageAlert?.Invoke(this, messageText);
            return false;
        }

        public void OnResetDialogState(IWebBrowser chromiumWebBrowser, IBrowser browser)
        {

        }
    }
}
